package com.xiaxiang.xiawan.FunPhoto;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dg.acb.utils.configdata.XXConstants;
import com.donggua.aichebao.commonui.photo.PhotoSelectView;
import com.donggua.client.fileserverlibrary.FileServerUpload;
import com.pbq.imagepicker.ImagePicker;
import com.pbq.imagepicker.VideoPicker;
import com.pbq.imagepicker.bean.ImageItem;
import com.pbq.imagepicker.bean.VideoItem;
import com.pbq.imagepicker.ui.image.ImageGridActivity;
import com.pbq.imagepicker.ui.video.VideoGridActivity;
import com.vondear.rxtools.view.dialog.RxDialogLoading;
import com.xiaxiang.ar.ARCloud.ARCloudEditor;
import com.xiaxiang.xiawan.R;
import com.xiaxiang.xiawan.XXMainApplication;
import com.xx.xiawan.net.DGJsonResult;
import com.xx.xiawan.net.DGRequestListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class FunPhotoCreate extends Activity implements View.OnClickListener {
    private PhotoSelectView photoSelect;
    private ImageView pickImage;
    private ImageView pickVideo;
    private ImagePicker imagePicker;
    private VideoPicker videoPicker;
    private RxDialogLoading dialogLoading;
    private String photoName = null;
    private String videoName = null;
    private String photoPath = null;
    private String videoPath = null;
    private int syncFlag = 0;
    private Handler mUiHandler;
    private TextView TitleBarRigthText;
    final  public static int RES_CODE = 0x90;
    private final int MSG_DIALOG_HIDE = 0x01;
    private final int MSG_DIALOG_SHOW = 0x02;
    private final int MSG_RES_SUCCESS = 0x10;
    private final int MSG_RES_ERROR = 0x11;
    private XXMainApplication app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_fun_photo_create);
        app = XXMainApplication.getInstance();
        initView();
        setUiHandler();
    }

    private void setUiHandler(){
        mUiHandler = new Handler(){
            public void handleMessage(Message msg){
                super.handleMessage(msg);
                switch (msg.what){
                    case  MSG_DIALOG_HIDE:
                        if(dialogLoading.isShowing()){
                            dialogLoading.hide();
                        }
                        break;

                    case  MSG_DIALOG_SHOW:
                        dialogLoading.show();
                        break;

                    case  MSG_RES_SUCCESS:
                        if(dialogLoading.isShowing()){
                            dialogLoading.hide();
                            dialogLoading.dismiss();
                        }
                        String res = (String) msg.obj;
                        Toast.makeText(getActivity(), "创建成功", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent();
                        intent.putExtra("item",res);
                        setResult(RES_CODE, intent);
                        Log.i("drj1", res);
                        finish();

                        break;

                    case  MSG_RES_ERROR:
                        String errorMsg = (String) msg.obj;
                        if (errorMsg != null && errorMsg.length() > 0) {
                            Toast.makeText(getActivity(), "创建失败：" + errorMsg, Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(getActivity(), "创建失败：网络错误！", Toast.LENGTH_SHORT).show();
                        }
                        if(dialogLoading.isShowing()){
                            dialogLoading.hide();
                        }
                        break;

                    default:
                        break;
                }
            }
        };
    }

    Activity getActivity() {
        return this;
    }

    private void initView() {
        ((TextView) findViewById(R.id.TitleBarText)).setText("创建应用");
        TitleBarRigthText = findViewById(R.id.TitleBarRigthText);
        TitleBarRigthText.setText("保存");
        TitleBarRigthText.setVisibility(View.VISIBLE);
        TitleBarRigthText.setOnClickListener(this);
        ImageView btn_back = findViewById(R.id.TitleBarLeftImg);
        btn_back.setVisibility(View.VISIBLE);
        btn_back.setOnClickListener(this);
        findViewById(R.id.btn_save).setOnClickListener(this);

        videoPicker = VideoPicker.getInstance();
        videoPicker.setMultiMode(false);
        pickVideo = findViewById(R.id.pickVideo);
        pickVideo.setOnClickListener(this);
        pickImage = findViewById(R.id.pickImage);
        pickImage.setOnClickListener(this);
        dialogLoading = new RxDialogLoading(this);
        dialogLoading.setCancelable(false);
    }

    @Override
    public void onClick(View view) {
        Intent it;
        switch (view.getId()) {
            case R.id.pickVideo:
                it = new Intent(FunPhotoCreate.this, VideoGridActivity.class);
                startActivityForResult(it, 300);
                break;
            case R.id.pickImage:
                it = new Intent(FunPhotoCreate.this, ImageGridActivity.class);
                startActivityForResult(it, 100);
//                photoSelect = new PhotoSelectView(getActivity());
                break;
            case R.id.TitleBarRigthText:
            case R.id.btn_save:
                TextView edit_name = findViewById(R.id.edit_name);
                final String name = edit_name.getText().toString();
                int i = name.length();
                if (name == null || name.length() <= 0) {
                    Toast.makeText(getActivity(), "请输入名称", Toast.LENGTH_SHORT).show();
                    break;
                }

                if (photoPath == null || photoPath.length() <= 0) {
                    Toast.makeText(getActivity(), "请上传识别图", Toast.LENGTH_SHORT).show();
                    break;
                }

                if (videoPath == null || videoPath.length() <= 0) {
                    Toast.makeText(getActivity(), "请上传目标视频", Toast.LENGTH_SHORT).show();
                    break;
                }

                sendMessage(MSG_DIALOG_SHOW,"");
                FileServerUpload.IUploadComplete iUploadComplete = new FileServerUpload.IUploadComplete() {
                    public void onUploadSuccess(String fileKey, String fileHash, int code) {
                        Log.i("up", "compressWithLs: code: " + code + " fileKey: " + fileKey + " fileHash:" + fileHash);
                        switch (code) {
                            case 0:
                                syncFlag = syncFlag | 1;
                                photoName = fileKey;
                                break;

                            case 1:
                                syncFlag = syncFlag | 2;
                                videoName = fileKey;
                                break;
                        }
                        if (syncFlag == 3 ) {

                            JSONObject mJson;
                            mJson = new JSONObject();
                            try {
                                mJson.put("name", name);
                                mJson.put("userName", app.getUserName());
                                mJson.put("targetName", photoName);
                                mJson.put("materialUrl", videoName);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            Log.i("drj", mJson.toString());

                            ARCloudEditor.Register(getActivity(), mJson, XXConstants.URI_SAVE_FUN_PHOTO, app.getToken(), new DGRequestListener() {

                                @Override
                                public void onSuccess(DGJsonResult result) {
                                    sendMessage(MSG_RES_SUCCESS,result.result);

                                }

                                @Override
                                public void onError(String error) {
                                    JSONObject jsonObject = null;
                                    String errorMsg = null;
                                    try {
                                        jsonObject = new JSONObject(error);
                                        errorMsg = jsonObject.getString("errorMsg");
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                        errorMsg = error;
                                    }
                                    sendMessage(MSG_RES_ERROR,errorMsg);
                                }
                            });

                        }
                    }

                    @Override
                    public void onUploadFail(final String errorMsg, int code) {
                        sendMessage(MSG_RES_ERROR,errorMsg);
                    }
                };

                syncFlag = 0;
                FileServerUpload fileServerUpload = new FileServerUpload(FunPhotoCreate.this);
                fileServerUpload.setOnUploadSuccess(iUploadComplete);

                fileServerUpload.uploadPublic(photoPath, 0,app.getToken());
                fileServerUpload.uploadPublic(videoPath, 1,app.getToken());

                break;

            case R.id.TitleBarLeftImg:
                finish();
                break;

            default:
                break;
        }
    }

    private void compressWithLs(final File photos) {
        Log.e("drj", " compressWithLs file is " + photos);
        Luban.with(this)
                .load(photos)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        Log.i("drj", "compressWithLs ok: " + file.length());

                        Bitmap bitmap = pickImage.getDrawingCache();
                        pickImage.setImageBitmap(null);
                        if (bitmap != null && !bitmap.isRecycled()) {
                            bitmap.recycle();
                        }

                        Glide.with(FunPhotoCreate.this).load(Uri.fromFile(file)).into(pickImage);
                        photoPath = file.getPath();
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("size", "onActivityResult 1122");
        if (resultCode == ImagePicker.RESULT_IMAGE_ITEMS) {
            if (data != null && requestCode == 100) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                String filePath = images.get(0).path;
                File file = new File(filePath);
                if(file.exists() ) {
                    compressWithLs(file);
                }else {
                    Toast.makeText(this, "文件已损坏", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        } else if (resultCode == VideoPicker.RESULT_VIDEO_ITEMS) {
            if (data != null && requestCode == 300) {
                ArrayList<VideoItem> videos = (ArrayList<VideoItem>) data.getSerializableExtra(VideoPicker.EXTRA_RESULT_VIDEO_ITEMS);
                videoPath = videos.get(0).path;
                File file = new File(videoPath);
                Glide.with(FunPhotoCreate.this).load(Uri.fromFile(file)).into(pickVideo);
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void sendMessage(int what, Object obj) {
        Message msg = mUiHandler.obtainMessage();
        msg.what = what;
        if (obj != null)
            msg.obj = obj;
        mUiHandler.sendMessage(msg);
    }

}
